from django.contrib.auth.hashers import make_password
from django.shortcuts import render

# 注册
# # 导入模块
from django.shortcuts import render, redirect
from django.http import HttpResponse, JsonResponse
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, logout
from django.contrib.auth import login as django_login
from rest_framework_simplejwt.tokens import RefreshToken
from django.shortcuts import get_object_or_404


def register(request):
    if request.method == 'GET':
        return JsonResponse({
            'code': 403,
            'msg': '被禁止的请求'
        })

    elif request.method == 'POST':
        # 获取参数
        user_name = request.POST.get('username', '')
        pwd = request.POST.get('password', '')
        email = request.POST.get('email', '')

        # 用户已存在
        if User.objects.filter(username=user_name):
            return JsonResponse({
                'code': 200,
                'msg': '用户已存在'
            })
        # 用户不存在
        else:
            # 使用User内置方法创建用户
            user = User.objects.create_user(
                username=user_name,
                password=pwd,
                email=email,
                is_staff=1,
                is_active=1,
                is_superuser=0
            )

            return JsonResponse({
                'code': 200,
                'msg': '用户注册成功'
            })

    else:
        return JsonResponse({
            'code': 403,
            'msg': '被禁止的请求'
        })


# 登录
def login(request):
    if request.method == 'POST':
        # 获取参数
        user_name = request.POST.get('username', '')
        pwd = request.POST.get('password', '')

        # 用户已存在
        if User.objects.filter(username=user_name):
            # 使用内置方法验证
            user = authenticate(username=user_name, password=pwd)

            # 验证通过
            if user:
                # 用户已激活
                if user.is_active:
                    # 用户验证成功，生成 JWT 令牌
                    refresh = RefreshToken.for_user(user)
                    access_token = str(refresh.access_token)
                    # 登录用户
                    django_login(request, user)
                    # # 使用Token
                    # token, created = Token.objects.get_or_create(user=user)
                    #
                    # # 登录用户
                    # django_login(request, user)
                    return JsonResponse({
                        'code': 200,
                        'msg': '登录成功',
                        'user_id': user.id,
                        'token': access_token,  # 返回Token给前端
                        'isAdmin': user.is_superuser
                    })
                # 未激活
                else:
                    return JsonResponse({
                        'code': 200,
                        'msg': '用户未激活'
                    })

            # 验证失败
            else:
                return JsonResponse({
                    'code': 403,
                    'msg': '用户认证失败'
                })

        # 用户不存在
        else:
            return JsonResponse({
                'code': 403,
                'msg': '用户不存在'
            })
    else:
        return JsonResponse({
            'code': 403,
            'msg': '被禁止的请求'
        })


# 登出
def logout(request):
    logout(request)
    return redirect('/basuc/login')


# 查询所有用户
def get_all_users(request):
    if request.method == 'GET':
        users = User.objects.all()
        user_list = [{'id': user.id, 'username': user.username, 'email': user.email, 'password': make_password(user.password)} for user
                     in users]
        return JsonResponse({'code': 200, 'users': user_list})
    else:
        return JsonResponse({'code': 403, 'msg': '被禁止的请求'})


# 修改用户

def update_user(request, user_id):
    if request.method == 'POST':
        user = get_object_or_404(User, id=user_id)
        new_username = request.POST.get('new_username', '')
        new_password = request.POST.get('new_password', '')
        new_email = request.POST.get('new_email', '')

        if new_username:
            user.username = new_username
        if new_password:
            user.set_password(new_password)
        if new_email:
            user.email = new_email

        user.save()
        return JsonResponse({'code': 200, 'msg': '用户信息修改成功'})
    else:
        return JsonResponse({'code': 403, 'msg': '被禁止的请求'})


# 删除用户

def delete_user(request, user_id):
    if request.method == 'POST':
        user = get_object_or_404(User, id=user_id)
        user.delete()
        return JsonResponse({'code': 200, 'msg': '用户删除成功'})
    else:
        return JsonResponse({'code': 403, 'msg': '被禁止的请求'})


def get_user(request, user_id):
    if request.method == 'GET':
        user = get_object_or_404(User, id=user_id)
        user_info = {
            'id': user.id,
            'username': user.username,
            'email': user.email,
            'is_staff': user.is_staff,
            'is_active': user.is_active,
            'is_superuser': user.is_superuser,
            'password':make_password(user.password)
        }
        return JsonResponse({'code': 200, 'user': user_info})
    else:
        return JsonResponse({'code': 403, 'msg': '被禁止的请求'})
